package JUC.forkjoin;

import java.util.concurrent.RecursiveTask;

/**
 * 求和计算
 * forkjoin
 */
public class ForkJoinDemo extends RecursiveTask<Long> {

    private long start;//1
    private Long end;//10000000000

    //临界值
    private Long temp = 10000L;

    public ForkJoinDemo(long start, Long end) {
        this.start = start;
        this.end = end;
    }

    //计算方法
    @Override
    protected Long compute() {
        if ((end - start) > temp) {
            Long sum =0L;
            //分支合并计算
            for (Long i = start; i <end; i++) {
                sum += i;
            }
            System.out.println(sum);
            return sum;
            }else{
            //forkjoin
            long middle =(start+end) /2; //中间值
            ForkJoinDemo Task1 = new ForkJoinDemo(start, middle);
            ForkJoinDemo Task2 = new ForkJoinDemo(start, middle);
            //计算类继承forkjoinTask

            Task1.fork();//拆分任务，把任务压入线程队列
            Task2.fork();//拆分任务，把任务压入线程队列
            return Task1.join()+ Task2.join();
        }


//  public static void main(String[] args) {
//        int sum=0;
//        for (int i = 0; i <10_0000_0000; i++) {
//            sum+=i;
//        }
//        System.out.println(sum);
        }
    }

